<template>
  <div class="admin-knowledge-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>知识库管理</h1>
        <div class="breadcrumb">
          <span>首页</span> / <span>内容管理</span> / <span class="current">知识库管理</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加知识
        </el-button>
        <el-button @click="refreshList">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="选择分类" clearable>
            <el-option label="英语语法" :value="1" />
            <el-option label="英语词汇" :value="2" />
            <el-option label="英语口语" :value="3" />
            <el-option label="英语听力" :value="4" />
            <el-option label="英语阅读" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="data-table-card">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="danger" @click="batchDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除 ({{ selectedRows.length }})
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="dataList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" width="250" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" show-overflow-tooltip min-width="300" />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="success" @click="showEditDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ total }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="form.content" 
            placeholder="请输入内容" 
            type="textarea" 
            :rows="6"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted,component } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import knowledgeApi from '@/api/knowledge'

// 数据相关
const dataList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  title: '',
  categoryId: null
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加知识')
const form = reactive({
  id: null,
  title: '',
  content: '',
  categoryId: null,
  tag: []
})
const formRef = ref(null)
const formRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 200, message: '标题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '内容长度在 10 到 5000 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 生命周期钩子
onMounted(() => {
  fetchDataList()
})

// 获取数据列表
const fetchDataList = async () => {
  try {
    console.debug("获取课程列表")
    const response = await knowledgeApi.getKnowledgeList({
      ...searchForm,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    console.debug("获取课程列表")
    console.debug(response)
    console.debug(response.data)
    if (response.code === 100) {
      dataList.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取数据列表失败')
    }
  } catch (error) {
    ElMessage.error('获取数据列表失败:' + error.message)
  }
}



// 搜索
const search = () => {
  currentPage.value = 1
  fetchDataList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'categoryId' ? null : ''
  })
  currentPage.value = 1
  fetchDataList()
}

// 刷新列表
const refreshList = () => {
  fetchDataList()
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchDataList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchDataList()
}

// 选择行处理
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加知识'
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  dialogTitle.value = `编辑知识:${row.title}`
  
  // 设置表单数据
  Object.assign(form, {
    id: row.id,
    title: row.title,
    content: row.content,
    categoryId: row.categoryId,
    tag: [...row.tag]
  })
  
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    title: '',
    content: '',
    categoryId: null,
    tag: []
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 准备提交数据
    const submitData = {
      title: form.title,
      content: form.content,
      categoryId: form.categoryId,
      tag: form.tag
    }
    
    let response
    if (!form.id) {
      // 添加知识
      response = await knowledgeApi.addKnowledge(submitData)
    } else {
      // 编辑知识
      response = await knowledgeApi.updateKnowledge(form.id, submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(`${form.id ? '编辑' : '添加'}知识成功`)
      closeDialog()
      fetchDataList()
    } else {
      ElMessage.error(response.message || `${form.id ? '编辑' : '添加'}知识失败`)
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      return // 表单验证失败,不做处理
    }
    ElMessage.error(`${form.id ? '编辑' : '添加'}知识失败:` + error.message)
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除知识「${row.title}」吗?此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await knowledgeApi.deleteKnowledge(row.id)
      
      if (response.code === 200) {
        ElMessage.success('删除知识成功')
        fetchDataList()
      } else {
        ElMessage.error(response.message || '删除知识失败')
      }
    } catch (error) {
      ElMessage.error('删除知识失败:' + error.message)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的知识')
    return
  }
  
  const titles = selectedRows.value.map(row => row.title).join('、')
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个知识吗?\n${titles}`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      const response = await knowledgeApi.batchDeleteKnowledge(ids)
      
      if (response.code === 200) {
        ElMessage.success('批量删除知识成功')
        fetchDataList()
      } else {
        ElMessage.error(response.message || '批量删除知识失败')
      }
    } catch (error) {
      ElMessage.error('批量删除知识失败:' + error.message)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 工具方法
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
}

const getCategoryName = (categoryId) => {
  const categoryMap = {
    1: '英语语法',
    2: '英语词汇',
    3: '英语口语',
    4: '英语听力',
    5: '英语阅读'
  }
  return categoryMap[categoryId] || '未知'
}

const getCategoryTagType = (categoryId) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info'
  }
  return typeMap[categoryId] || 'info'
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})
</script>

<style lang="scss" scoped>
.admin-knowledge-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 40px);
}

// 页面头部样式
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-content {
    .breadcrumb {
      color: #606266;
      font-size: 14px;
      margin-top: 8px;
      
      .current {
        color: #409eff;
        font-weight: 500;
      }
    }
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
}

// 搜索筛选卡片样式
.search-filter-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .search-form {
    .el-form-item {
      margin-right: 10px;
    }
  }
}

// 数据表格卡片样式
.data-table-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

// 工具栏样式
.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

// 分页容器样式
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  
  .pagination-info {
    color: #606266;
    font-size: 14px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .admin-knowledge-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-filter-card {
    .search-form {
      .el-form-item {
        margin-right: 0;
        margin-bottom: 15px;
        width: 100%;
      }
    }
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }
}
</style>
